package aaa.database;

import java.util.Enumeration;
import java.util.ResourceBundle;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils.InsertHelper;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.util.Log;

public class InitialLocations implements DatabaseConstants {

	private static final String BUNDLE_NAME = "aaa.database.initialValues"; //$NON-NLS-1$

	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
			.getBundle(BUNDLE_NAME) ;

	public static int nextId = 0 ;

	private InitialLocations() {}

	public static void testDatabase(Context context, CreateDatabases cd) {
		Cursor institutionCount = null ;
		Cursor roomCount = null ;
		SQLiteDatabase db = cd.getWritableDatabase() ;
		try {
			institutionCount = db.query(false, TABLE_INSTITUTION, 
					new String[]{"COUNT(*)"}, // columns
					null, // selection
					null, // selectionArgs
					null, // group by
					null, // having
					null, // order by
					null) ;//limit
			roomCount = db.query(false, TABLE_ROOM, 
					new String[]{"COUNT(*)"}, // columns
					null, // selection
					null, // selectionArgs
					null, // group by
					null, // having
					null, // order by
					null) ;//limit
			if (!institutionCount.moveToNext() || (institutionCount.getInt(0) != 18)) {
				throw new Exception() ;
			}// if 
			if (!roomCount.moveToNext() || (roomCount.getInt(0) != 1786)) {
				throw new Exception() ;
			}// if
		} catch (Exception e) {
			InitialLocations.cleanDatabase(db) ;
			InitialLocations.fillDatabase(context, cd) ;
		} finally {
			if (institutionCount != null) {
				institutionCount.close() ;
			}// if
			if (roomCount != null) {
				roomCount.close() ;
			}// if
		}// try
	}
	
	private static void cleanDatabase(SQLiteDatabase db) {
		try {
			db.delete(TABLE_INSTITUTION, null, null) ;
		} catch (Exception e) {/** Nothing to be done. */}//try
		try {
			db.execSQL("DROP TABLE "+TABLE_INSTITUTION+";") ;
		} catch (Exception e) {/** Nothing to be done. */}//try
		try {
			db.delete(TABLE_ROOM, null, null) ;
		} catch (Exception e) {/** Nothing to be done. */}//try
		try {
			db.execSQL("DROP TABLE "+TABLE_ROOM+";") ;
		} catch (Exception e) {/** Nothing to be done. */}//try
		db.execSQL(CreateDatabases.CREATE_INSTITUTION_BDD);
		db.execSQL(CreateDatabases.CREATE_ROOM_BDD);
	}

	private static void fillDatabase(Context context, final CreateDatabases cd) {
		final ProgressDialog updateDialog = ProgressDialog.show(context, 
				"Chargement", "Préparation pour la première utilisation ...", 
				true, false, null) ;
		Log.d("aaa", "Dialog displayed") ;
		new AsyncTask<Void, Object, Void>() {
			@Override
			protected Void doInBackground(Void... params) {
				int nInsertedRooms = 0, totalNRooms = 1786, oldPct = -1 ;
				Enumeration<String> keys = RESOURCE_BUNDLE.getKeys() ;
				
				SQLiteDatabase db = cd.getWritableDatabase() ;
				InsertHelper insertHelper = new InsertHelper(db, TABLE_ROOM) ;
				db.beginTransaction() ;
				
				while (keys.hasMoreElements()) {
					String instId = keys.nextElement() ;
					String[] values = RESOURCE_BUNDLE.getString(instId).split("/") ;
					String instName = values[0] ;
					InitialLocations.insertInstitution(db, instId, instName) ;
					int nRooms = values.length-1;
					String[] roomNames = new String[nRooms] ;
					System.arraycopy(values, 1, roomNames, 0, nRooms) ;
					for(String roomName : roomNames) {
						InitialLocations.insertRoom(insertHelper, instId, roomName) ;
						nInsertedRooms+=100 ;
						int pct = nInsertedRooms/totalNRooms ;
						if (pct%5 == 0 && pct != oldPct) {
							this.publishProgress(pct) ;
							oldPct = pct ;
						}// if
					}// for
				}// while
				db.setTransactionSuccessful() ;
				db.endTransaction() ;
				db.close() ;	
					
				updateDialog.dismiss() ;
				return null ;
			}
			@Override
			protected void onProgressUpdate(Object... values) {
				updateDialog.setMessage(String.format(
						"Préparation pour la première utilisation ... %d %%", values[0])) ;
				Log.d("aaa", "Progrès : "+values[0]) ;
			}
		}.execute() ;
	}

	private static long insertInstitution(SQLiteDatabase db, String id, String instName) {
		ContentValues values = new ContentValues();
		values.put(INST_COL_ID, Integer.parseInt(id));
		values.put(INST_COL_NAME, instName);
		return db.insert(TABLE_INSTITUTION, null, values) ;
	}

	private static long insertRoom(InsertHelper insertHelper, String instId, String roomName) {
		insertHelper.prepareForInsert() ;
		insertHelper.bind(1+ROOM_NUM_COL_ID, InitialLocations.nextId++) ;
		insertHelper.bind(1+ROOM_NUM_COL_INSTITUTION, Integer.parseInt(instId)) ;
		insertHelper.bind(1+ROOM_NUM_COL_NAME, roomName) ;
		return insertHelper.execute() ;
	}

}
